package GUI;


import javax.swing.AbstractButton;
import javax.swing.BoxLayout;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JButton;
import javax.swing.JSeparator;
import javax.swing.SpringLayout;
import javax.swing.SwingConstants;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.HeadlessException;
import java.awt.Image;
import java.awt.Insets;
import java.awt.Toolkit;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.io.IOException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Vector;

import javax.swing.JTextField;
import javax.swing.border.BevelBorder;
import javax.swing.border.EtchedBorder;
import javax.swing.border.LineBorder;
import javax.swing.border.TitledBorder;

import DataObjects.AddWorkinHoursINandOUT;
import DataObjects.User;
import Messages.MessageAddCommentAboutOverHrs;
import Messages.MessageAddWorkingHours;
import Messages.MessageAddWorkingHoursReply;
import Messages.MessageSavingReply;
import Messages.MessageShowAllSuppliers;
import Messages.MessageShowAllSuppliersReply;
import Messages.MessageShowAllWorkHours;
import Messages.MessageShowAllWorkHoursReply;
import DataObjects.CheckHoursInDate;
/**
 * 
 * @author Andrey,Igor,jeka
 * Class for creation window that includes two buttons for choose action(Enter or Exit) and button Back
 *
 */
public class PfClock_In_Out_Second extends JPanel {
	
	/**
	 * 
	 */
	private static final long serialVersionUID = -8998998732944713937L;
	private MainMenu mainMenu;
	private JButton enterButton;
	private JButton exitButton;
	private JPanel underPanel;
	private JPanel underPanel2;
	private JPanel enterPanel;
	private JPanel dohPanel;
	private JPanel exitPanel;
	private JPanel middlePanel;
	private JPanel topPanel;
	private Vector<String> workHours;
	private Vector<String> wrkHrs;
	private int flag;
	private int flagHrs;
	private MessageAddWorkingHoursReply result1;
	private MessageAddWorkingHoursReply result3;
	private String employeeID;
	private User empDetails;	
	private int x;
	private int y;
	private AddWorkinHoursINandOUT Inout;
	
	private Dimension screenSize;
	
	public PfClock_In_Out_Second(MainMenu mm,int flagButt,String empID,User empDet)
	{
		super();
		screenSize = Toolkit.getDefaultToolkit().getScreenSize();
		x=screenSize.width;
		y=screenSize.height;
		this.mainMenu=mm;
		this.flag=flagButt;
		this.employeeID=empID;
		this.empDetails=empDet;
		this.setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
		this.flagHrs=0;
		
		//   workHours = new Vector<String>();
		
		initialize();
		
	}
	
	
	
	private void initialize()
	{
		
		add(getTopPanel());
		add(getUnderPanel1());
	//	add(getUnderPanel2());
		
		add(getMiddlePanel());
		
	}
	
	
	//====================== panels for UnderPanel	========================================
	
	/**
	 * Method for creation JPanel underPanel that consist of two panels(EnterPanel and ExitPanel)
	 * @return underPanel
	 */
	private JPanel getUnderPanel1()            
	{
		underPanel=new JPanel();
		underPanel.setLayout(new BoxLayout(underPanel, BoxLayout.X_AXIS));
		underPanel.add(getEnterPanel());
		underPanel.add(getExitPanel());
		
		return underPanel;
	}
	
	//--------------------------------------------------------------------
/*	private JPanel getUnderPanel2()                  //vernut
	{
		underPanel2=new JPanel();
		underPanel2.setLayout(new BoxLayout(underPanel2, BoxLayout.X_AXIS));
		underPanel2.add(getTime2Panel());
		 
		
		return underPanel2;
	}*/
	
	/**
	 * Method for creation JPanel enterPanel and  gets the button from method getEnterButton and adds it the enterPanel
	 * @return enterPanel
	 */
	private JPanel getEnterPanel()           
	{
		enterPanel=new JPanel();
		GridBagLayout gbll = new GridBagLayout();    
		gbll.rowWeights = new double[]{1.0};
		enterPanel.setLayout(gbll);
		GridBagConstraints gbc1 = new GridBagConstraints();
		
				
		gbc1.gridx=0;
		gbc1.gridy=0;
		
		gbc1.insets = new Insets(0,0,100,0);
		enterPanel.add(getEnterButton(),gbc1);
			
		return enterPanel;
	}
	
	/**
	 * Method for creation JButton enterButton that saves date and time of the beginning of work of the employee
	 * @return enterButton
	 */
	private JButton getEnterButton()
	{
		String num;
		Icon enterIcon = new ImageIcon("arrowEnter.png");
		Image img = ((ImageIcon) enterIcon).getImage() ;  
		   Image newimg = img.getScaledInstance( x/12,y/8,  java.awt.Image.SCALE_SMOOTH ) ;  
		   enterIcon = new ImageIcon( newimg );
		   enterButton=new JButton("כניסה",enterIcon);
		enterButton.setFont(new Font("Tahoma", Font.ROMAN_BASELINE, 23));
		enterButton.setForeground(Color.BLACK);
		//enterButton.setPreferredSize(new Dimension(x/12,y/8));
		if(flag==0)                                                      //if button EXIT is enable ENTER is not enable
			enterButton.setEnabled(false);
		else
			enterButton.setEnabled(true);
		
		enterButton.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent e) {
				
				 workHours = new Vector<String>();
				 Date dat = new Date();
				 
				 
				  DateFormat df = new SimpleDateFormat("yyyy/MM/dd");
				  DateFormat df1 = new SimpleDateFormat("HH:mm:ss");
				 
				  String   data = df.format(dat);
				  String   time = df1.format(dat);
				 
				  Calendar calCurrent=Calendar.getInstance();							
				  long time1 = calCurrent.getTimeInMillis() + calCurrent.getTimeZone().getOffset(calCurrent.getTimeInMillis());
			     
			     	  
				 workHours.add(employeeID);
				 workHours.add(data);
				 workHours.add(time);
				 workHours.add(null);			 
				 workHours.add("null");   //etogo ne hvataet v AddNew !!!!!!!!!!!!!!!!!!!!!
		    	 workHours.add("null");    //etogo ne hvataet v AddNew !!!!!!!!!!!!!!!!!!!!!
				 
			   
					MessageAddWorkingHours mess = new MessageAddWorkingHours(workHours);   // time1 
					try {
						
						mainMenu.ms.client.sendToServer(mess);
						MessageSavingReply result = (MessageSavingReply)mainMenu.ms.client.GetMessage();
						 
					if (result.getResult()== '0')
				    	{
				    		JOptionPane.showMessageDialog(null,"בעיית תקשורת 03");
				    	}
				    	
				    else 	
				    	{
				    		JOptionPane.showMessageDialog(null,"הנתונים נשמרו בהצלחה");
				    		enterButton.setEnabled(false);                         
				    		//after press on button ENTER this button there is NOT ENABLED
				    		exitButton.setEnabled(true);                           
				    		//and button EXIT - ENABLED
				       //	underPanel2.add(getTime2Panel());          //vernut
				    		
				    	}
				    	
				    	
					} catch (IOException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					}
		
			 		
			}
		});
		
		return enterButton;
		
	}
	
	
	
	/**
	 * Method for creation JPanel exitPanel and  gets the button from method getExitButton and adds it the exitPanel
	 * @return exitPanel
	 */
	private JPanel getExitPanel()              
	{
		
		exitPanel=new JPanel();
		GridBagLayout gblll = new GridBagLayout();    
		exitPanel.setLayout(gblll);
		GridBagConstraints gbc3 = new GridBagConstraints();
		
		gbc3.gridx=0;
		gbc3.gridy=0;
		
		gbc3.insets = new Insets(0,0,100,0);
		exitPanel.add(getExitButton(),gbc3);
		
		return exitPanel;
	}
	
	/**
	 * Method for creation JButton exitButton that saves date and time of the end of work of the employee and
	 * causes the new class AccessClockInClockOut to display total number of working hours
	 * @return exitButton
	 */
	private JButton getExitButton()
	{
		Icon exitIcon = new ImageIcon("red_arrow_down_left.png");
		Image img = ((ImageIcon) exitIcon).getImage() ;  
		   Image newimg = img.getScaledInstance( x/12,y/8,  java.awt.Image.SCALE_SMOOTH ) ;  
		   exitIcon = new ImageIcon( newimg );
		   exitButton=new JButton("יציאה",exitIcon);
		
		exitButton.setFont(new Font("Tahoma", Font.ROMAN_BASELINE, 23));
		exitButton.setForeground(Color.BLACK);
		//exitButton.setPreferredSize(new Dimension(x/12,y/8));
		if(flag==0)
			exitButton.setEnabled(true);
		else
			exitButton.setEnabled(false);
	   	    exitButton.addActionListener(new java.awt.event.ActionListener() {
			 

			public void actionPerformed(java.awt.event.ActionEvent e) {
				 workHours = new Vector<String>();
				 Date dat = new Date();
				 DateFormat df = new SimpleDateFormat("yyyy/MM/dd");
				  DateFormat df1 = new SimpleDateFormat("HH:mm:ss"); 
				  DateFormat dfmonth = new SimpleDateFormat("MM");
				  
				  String   data = df.format(dat);
				  String   time = df1.format(dat); 
			      String month = dfmonth.format(dat); 
				  
				 workHours.add(employeeID);
				 workHours.add(data);
				 workHours.add(time);
				 workHours.add("1");                             //  exit button 
				 workHours.add("NULL");
				 workHours.add(month);
				 
				MessageAddWorkingHours mess = new MessageAddWorkingHours(workHours);  
				    //send to server(empID,data,time) of  employee 
				try {
					mainMenu.ms.client.sendToServer(mess);
					MessageSavingReply result = (MessageSavingReply)mainMenu.ms.client.GetMessage();  
					
			        result1 = (MessageAddWorkingHoursReply)mainMenu.ms.client.GetMessage(); 
			        //calculate the work hours of this day and this month
				
			        
			         
			    	if (result.getResult()== '0')
			    	{
			    		JOptionPane.showMessageDialog(null,"בעיית תקשורת. נסה שוב ");
			    	}
			    	
			    	else 
			    	{
			    		exitButton.setEnabled(false);
			    		enterButton.setEnabled(true);
			    	  		 
			    		 
			    	}
				} catch (IOException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
				//------------
				 CheckHoursInDate chk = new CheckHoursInDate(result1.getDatesHours());
	    		
	    		//try {
					try {
						if(chk.CalculateDayHours())       // if number of hours >12 , delete clockOut - Lo buza iezia
						{							
						 
						    wrkHrs= new Vector<String>();
							wrkHrs.add(employeeID);
							wrkHrs.add(data);
							wrkHrs.add("NULL");
							wrkHrs.add("1");        //  exit button 
							wrkHrs.add("NULL");
							wrkHrs.add(month);
							
							flagHrs=1;
						
						 	 MessageAddWorkingHours mess2 = new MessageAddWorkingHours(wrkHrs);  
							
							 try {
									mainMenu.ms.client.sendToServer(mess2);
									MessageSavingReply result2 = (MessageSavingReply)mainMenu.ms.client.GetMessage();  
									 
							         result3 = (MessageAddWorkingHoursReply)mainMenu.ms.client.GetMessage(); 
							       
							        //calculate the work hours of this day and this month
							        if (result2.getResult()== '0')
							    	{
							    		JOptionPane.showMessageDialog(null,"בעיית תקשורת. נסה שוב ");
							    	}
							       
						    	 	
						    	  AccessClockInClockOut access=new AccessClockInClockOut(mainMenu,result3.getWorkHours(),result3.getWorkMonthHours(), flagHrs);
						    	 	
						    	 	 if(access.getTempHours()>16)                              // esli v kakuiu nibud datu sdelano bolshe 16 chasov - zapisat' harigu. 
							    		
						    		{
						    			 workHours.add("check num. of hours");     //יש חריגה בכמות שעות בתאריך הזה
						    			 
						    			
						    		}
									 else if(flagHrs==1)
									 {
										 workHours.add("exit warning");    //     ne bil sovershen vihod v etu v blijaishie 12 chasov posle vhoda
									 }
						    		else{ workHours.add("null"); }
								 
								
						
							 } catch (IOException e1) {
									// TODO Auto-generated catch block
									e1.printStackTrace();
								}
							 
						 
							
						}
					}  catch (ParseException e4) {
						// TODO Auto-generated catch block
						e4.printStackTrace();
					}  
					
					////win that show total number hours of day and month
					
					if(flagHrs!=1) {   AccessClockInClockOut access=new AccessClockInClockOut(mainMenu,result1.getWorkHours(),result1.getWorkMonthHours(), flagHrs);
					 
					 // esli v kakuiu nibud datu sdelano bolshe 16 chasov - zapisat' harigu. 
 		    		
					if(access.getTempHours()>16) {	  workHours.add("check num. of hours"); }	 	    	
	    			 
	 	    		else { workHours.add("null"); }
	    		 
	    		
					}
			 
	    		 
				
				if(!workHours.get(6).equals("null"))          // write comment about exceed number of working hours 
		    		
	    		{ 
					 
					MessageAddCommentAboutOverHrs mess1 = new MessageAddCommentAboutOverHrs(workHours,flagHrs);  
					mess1.setEmpDetails(workHours);       
				    //send to server(empID,data,time) of  employee 
				try {
					mainMenu.ms.client.sendToServer(mess1);
					 
					
				} catch (IOException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
				
				
	    		}
				
				
			}
		});
		return exitButton;
		
	}
	
	//====================== MiddlePanel	========================================
	
	/**
	 * Method for creation JPanel middlePanel and JButton okBtn for return to previous screen(PfClock_In_Out_First) without saving
	 * @return
	 */
	private JPanel getMiddlePanel()           //panel with button OK
	{
		middlePanel=new JPanel();
		Icon okIcon = new ImageIcon("exit-icon.png");
		Image img = ((ImageIcon) okIcon).getImage() ;  
		   Image newimg = img.getScaledInstance( x/12,y/8,  java.awt.Image.SCALE_SMOOTH ) ;  
		   okIcon = new ImageIcon( newimg );
		  // JButton  okBtn=new JButton(okIcon);yy
		JButton  okBtn=new JButton("חזרה",okIcon);   
		okBtn.setForeground(Color.BLUE);
		okBtn.setFont(new Font("Tahoma", Font.ROMAN_BASELINE, 23));
		//okBtn.setPreferredSize(new Dimension(x/10,y/9));
		//okBtn.setBorder(null);
		okBtn.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent e) {
				mainMenu.getContentPane().remove(((BorderLayout)mainMenu.getContentPane().getLayout()).getLayoutComponent(BorderLayout.CENTER));
 				mainMenu.getContentPane().add(new PfClock_In_Out_First(mainMenu), BorderLayout.CENTER);
 				mainMenu.getContentPane().validate();	
			}
		});
		GridBagLayout gbllll = new GridBagLayout();    
		middlePanel.setLayout(gbllll);
		GridBagConstraints gbc4 = new GridBagConstraints();
		
		gbc4.gridx=0;
		gbc4.gridy=0;
		
		gbc4.insets = new Insets(100,30,100,0);
		middlePanel.add(okBtn,gbc4);
		
		return middlePanel;
	}
	
	 
	/**
	 * Method for creation JPanel topPanel that consist of JPanel TimePanel that gets from method getTimePanel
	 *  and JPanel NamePanel that gets from getNamePanel
	 * @return JPanel topPanel
	 */
	private JPanel getTopPanel()           
	{
		topPanel=new JPanel();
		topPanel.setLayout(new BoxLayout(topPanel, BoxLayout.X_AXIS));
	//	topPanel.add(getTimePanel());                                      
		topPanel.add(getNamePanel());
		
		return topPanel;
	}
	
	/**
	 * Method for creation JPanel timePanel with digital clock(use class DigitalClock that return label clock)
	 * @return timePanel
	 */
/*	private JPanel getTimePanel()          
	{
		JPanel timePanel = new JPanel();
		timePanel.setLayout(new BoxLayout(timePanel, BoxLayout.Y_AXIS));
		DigitalClock dc = new DigitalClock();
		JLabel lblTime=new JLabel();
		lblTime=dc.getTimeLabel();
		timePanel.add(lblTime);
		timePanel.add(new JSeparator(SwingConstants.HORIZONTAL)); 		
		return  timePanel;
	}*/
	
	/**
	 * Method for creation JPanel namePanel and JLabel lblName for show name of employee that opened this window(employee
	 * that wants to begin or finish work) 
	 * @return JPanel namePanel
	 */
	private JPanel getNamePanel()        
	{
		JPanel namePanel = new JPanel();
		JLabel lblName=new JLabel();
		lblName.setText("שלום  "+empDetails.getName());
		lblName.setForeground(Color.BLACK);
		lblName.setFont(new Font("Tahoma", Font.PLAIN, 26));
		namePanel.add(lblName);
		return  namePanel;
	}
	
/*	private JPanel getTime2Panel()               //vernut
	{
		JPanel namePanel2 = new JPanel();
		JLabel lblName2=new JLabel();
		System.out.println("-----------");
		System.out.println(flag);
		
		System.out.println("workHours.isEmpty()");
		System.out.println(workHours.isEmpty());
		System.out.println(workHours);
		
		
		  if( !workHours.isEmpty())            //flag==0 &&           // nujen message dlia poluchenia poslednei knisi 
		  {
			 
		    lblName2.setText("כניסה אחרונה: " + workHours.get(2) +"  "+ workHours.get(1));  
		  	lblName2.setForeground(Color.BLACK);
		    lblName2.setFont(new Font("Tahoma", Font.ROMAN_BASELINE, 23));
		    lblName2.setHorizontalAlignment( SwingConstants.CENTER );
		    namePanel2.add(lblName2);
		  }  
		return  namePanel2;
	}
	*/
	
	
	
}